package com.bootdo.common.controller;

import com.bootdo.common.config.Constant;
import com.bootdo.common.domain.Area;
import com.bootdo.common.service.AreaService;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName AreaController
 * @Description 地区控制管理类
 * @Author xujiajia
 * @Date2019/9/11 17:13
 * @Version V1.0
 **/
@Controller
@RequestMapping("/common/area/")
public class AreaController extends BaseController {

    private String prefix = "common/area";

    @Autowired
    private AreaService areaService;

    @GetMapping()
    /*@RequiresPermissions("common:area:list")*/
    String area() {
        return prefix + "/area_list";
    }

    @ApiOperation(value="获取地区列表", notes="")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("common:area:list")
    public List<Area> list() {
        Map<String, Object> query = new HashMap<>(16);
        List<Area> areaList = areaService.list(query);
        return areaList;
    }

    @GetMapping("/add/{pId}")
    String add(@PathVariable("pId") Long pId, Model model) {
        model.addAttribute("pId", pId);
        if (pId == 0) {
            model.addAttribute("pName", "国家");
        } else {
            model.addAttribute("pName", areaService.get(pId).getAreaName());
        }
        return  prefix + "/add";
    }

    @GetMapping("/edit/{deptId}")
    String edit(@PathVariable("deptId") Long deptId, Model model) {
        Area area = areaService.get(deptId);
        model.addAttribute("area", area);
        if(Constant.DEPT_ROOT_ID.equals(area.getParentId())) {
            model.addAttribute("parentAreaName", "无");
        }else {
            Area parArea = areaService.get(area.getParentId());
            model.addAttribute("parentAreaName", parArea.getAreaName());
        }
        return  prefix + "/edit";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    public R save(Area area) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (areaService.insert(area) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    public R update(Area area) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (areaService.update(area) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     *//*
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("system:sysDept:remove")
    public R remove(Long deptId) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("parentId", deptId);
        if(sysDeptService.count(map)>0) {
            return R.error(1, "包含下级部门,不允许修改");
        }
        if(sysDeptService.checkDeptHasUser(deptId)) {
            if (sysDeptService.remove(deptId) > 0) {
                return R.ok();
            }
        }else {
            return R.error(1, "部门包含用户,不允许修改");
        }
        return R.error();
    }*/

    /**
     *
     * @Function 获取地区关系
     * @Author xujiajia
     * @Date 2019/9/11 17:17
     * @Param [request, response]
     * @Return void
     ***/
    @PostMapping(value = "/getareainfo")
    public void getAreaInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String areaId = request.getParameter("areaId");
        int areaLevel = Integer.parseInt(request.getParameter("areaLevel"));
        List<Area> areaInfoList = areaService.queryAreaInfo(areaId,"1");
        StringBuffer classString = new StringBuffer();
        String msg = "";
        if (areaLevel == 2) {
            msg = "请选择省份";
        }else if (areaLevel == 3) {
            msg = "请选择城市";
        }else if (areaLevel == 4) {
            msg = "请选择区县";
        }
        if (areaInfoList != null && areaInfoList.size() > 0) {
            classString.append("<option value>" + msg
                    + "</option>");
            for (Area areaInfo : areaInfoList) {
                if(areaId.startsWith(areaInfo.getAreaId().toString())) {
                    classString.append("<option value='")
                            .append(areaInfo.getAreaId()).append("' selected >");
                    classString.append(areaInfo.getAreaName()).append("</option>");
                }else {
                    classString.append("<option value='")
                            .append(areaInfo.getAreaId()).append("'>");
                    classString.append(areaInfo.getAreaName()).append("</option>");
                }
            }
        }
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(classString.toString());
        response.getWriter().flush();
    }

    /***
     * 获取地区的层级关系
     * @param request
     * @param response
     * @throws Exception
     */
    @PostMapping(value = "/getareainfofor")
    @ResponseBody
    public void getAreaList(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String parentId = request.getParameter("parentId");
        String areaId = request.getParameter("areaId");
        int areaLevel = Integer.parseInt(request.getParameter("areaLevel"));
        List<Area> areaInfoList = areaService.queryAreaInfo(parentId,"1");
        StringBuffer classString = new StringBuffer();
        String msg = "";
        if (areaLevel == 2) {
            msg = "请选择省份";
        }else if (areaLevel == 3) {
            msg = "请选择城市";
        }else if (areaLevel == 4) {
            msg = "请选择区县";
        }
        if (areaInfoList != null && areaInfoList.size() > 0) {
            classString.append("<option value>" + msg
                    + "</option>");
            for (Area areaInfo : areaInfoList) {
                if(areaId.startsWith(areaInfo.getAreaId().toString())) {
                    classString.append("<option value='")
                            .append(areaInfo.getAreaId()).append("' selected >");
                    classString.append(areaInfo.getAreaName()).append("</option>");
                }else {
                    classString.append("<option value='")
                            .append(areaInfo.getAreaId()).append("'>");
                    classString.append(areaInfo.getAreaName()).append("</option>");
                }
            }
        }
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(classString.toString());
        response.getWriter().flush();
    }

}
